package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.SetMealMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassNameReportServiceImpl
 * @Description TODO
 * @Author钰玟
 * @Date2025/2/17 下午4:14
 * @Version 1.0
 **/
@Service
public class ReportServiceImpl implements ReportService {

    public static final int START_INDEX = 7;
    @Autowired
    OrderMapper orderMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    DishMapper dishMapper;
    @Autowired
    SetMealMapper setMealMapper;

    @Autowired
    WorkspaceService workspaceService;
    /**
     * 获取营业额
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //计算日期
        while(! begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //"select sum(amount) from order where orderTime < ? and orderTime > ? and status = ?
            //建一个Map
            Map map = new HashMap();
            map.put("beginTime",  LocalDateTime.of(date, LocalTime.MIN));
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            map.put("status", Orders.COMPLETED);
            //查询
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //计算日期
        while(! begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //建一个Map
            Map map = new HashMap();
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            //查询
            //"select sum(id) from user where createTime < ?
            Integer userAmount  = userMapper.countByMap(map);


            map.put("beginTime",  LocalDateTime.of(date, LocalTime.MIN));

            //"select sum(id) from user where createTime < ? and createTime > ?

            Integer newUserAmount  = userMapper.countByMap(map);


            userAmount = userAmount == null ? 0 : userAmount;
            newUserAmount = newUserAmount == null ? 0 : newUserAmount;


            totalUserList.add(userAmount);
            newUserList.add(newUserAmount);
        }

        return UserReportVO.
                builder().
                dateList(StringUtils.join(dateList,",")).
                totalUserList(StringUtils.join(totalUserList,",")).
                newUserList(StringUtils.join(newUserList,",")).
                build();


    }

    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //计算日期
        while(! begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }


        List<Integer> totalOrderList = new ArrayList<>();
        List<Integer> ValidOrderList = new ArrayList<>();
        //总计的 有关数据
        Integer totalAmount = 0;
        Integer totalValidAmount = 0;

        for (LocalDate date : dateList) {
            Map map = new HashMap();
            map.put("beginTime",  LocalDateTime.of(date, LocalTime.MIN));
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            //查询所有订单数
            //select count(id) from orders where order_time > ? order_time < ?
            Integer total = orderMapper.countByMap(map);
            //累加 总订单数
            totalAmount+=total;
            totalOrderList.add(total);
            //查询有效订单数
            //select count(id) from orders where order_time > ? and order_time < ? and status = ?
            map.put("status",Orders.COMPLETED);
            Integer valid = orderMapper.countByMap(map);
            //累加 有效订单数
            totalValidAmount+=valid;
            ValidOrderList.add(valid);
        }
        //判断分母是否为零
        Double completeRate = 0.0;
        if (totalAmount !=0){
            completeRate = (totalValidAmount.doubleValue()/totalAmount);
        }



        return OrderReportVO.builder().
                dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(totalOrderList, ","))
                .validOrderCountList(StringUtils.join(ValidOrderList, ","))
                .totalOrderCount(totalAmount)
                .validOrderCount(totalValidAmount)
                .orderCompletionRate(completeRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO getOrdersTop10(LocalDate begin, LocalDate end) {
//        GoodsSalesDTO
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime =  LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);

        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        String nameList = StringUtils.join(names, ",");
        String numberList = StringUtils.join(numbers, ",");

        return SalesTop10ReportVO
                .builder()
                .numberList(numberList)
                .nameList(nameList)
                .build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //查询相关数据  最近30天的数据
        LocalDate beginDay = LocalDate.now().minusDays(30);
        LocalDate endDay = LocalDate.now().minusDays(1);

        BusinessDataVO businessData = workspaceService.getBusinessData
                (LocalDateTime.of(beginDay, LocalTime.MIN),
                LocalDateTime.of(endDay, LocalTime.MAX));
        //通过POI 写入到 excel文件中去
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //创建excel 操作对象
            XSSFWorkbook workbook = new XSSFWorkbook(resourceAsStream);
            XSSFSheet sheet1 = workbook.getSheet("Sheet1");
            //设置时间
            sheet1.getRow(1).getCell(1).setCellValue("时间"+beginDay+"至"+endDay);
            //设置概览数据
            //营业额
            sheet1.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            //订单完成率
            sheet1.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            //新增用户数
            sheet1.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            //有效订单
            sheet1.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            //平均客单价
            sheet1.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

            //明细数据
            //最近30天的日期列表
            List<LocalDate> dateList = new ArrayList<>();
            dateList.add(beginDay);
            while(!beginDay.equals(endDay) ){
                beginDay = beginDay.plusDays(1);
                dateList.add(beginDay);
            }
            System.out.println(dateList);
            int index = START_INDEX;
            for (LocalDate date : dateList) {


                BusinessDataVO data = workspaceService.getBusinessData(
                        LocalDateTime.of(date, LocalTime.MIN),
                        LocalDateTime.of(date, LocalTime.MAX));


                sheet1.getRow(index).getCell(1).setCellValue(date.toString());
                //营业额
                sheet1.getRow(index).getCell(2).setCellValue(data.getTurnover());
                //有效订单   getOrderCompletionRate
                sheet1.getRow(index).getCell(3).setCellValue(data.getValidOrderCount());
                //订单完成率
                sheet1.getRow(index).getCell(4).setCellValue(data.getOrderCompletionRate());
                //平均客单价
                sheet1.getRow(index).getCell(5).setCellValue(data.getUnitPrice());
                //新增用户数
                sheet1.getRow(index).getCell(6).setCellValue(data.getNewUsers());
                index++;
            }
            LocalDate date1 = LocalDate.now().plusDays(1);
            System.out.println(workspaceService.getBusinessData(
                    LocalDateTime.of(date1, LocalTime.MIN),
                    LocalDateTime.of(date1, LocalTime.MAX)
            ));


            ServletOutputStream os = response.getOutputStream();
            workbook.write(os);


        } catch (IOException e) {
            e.printStackTrace();
        }


        //通过输出流将文件下载到客户端浏览器中
    }
}
